<?php
/**
 * Created by JetBrains PhpStorm.
 * User: vander
 * Date: 6/13/13
 * Time: 9:55 PM
 * To change this template use File | Settings | File Templates.
 */
$bookId = $_GET['bookId'];
$result = "";

if(isset($bookId)){
///Doc collecitons.json
    $collectionFile = "collections.json";
    $handle = fopen($collectionFile, "r");
    $collectionStr = "";
    while(!feof($handle)){
        $collectionStr = $collectionStr . fgets($handle);
    }
    fclose($handle);

    $collection = json_decode($collectionStr);
    $numberOfBook = count($collection->books);
    for($i = 0; $i < $numberOfBook; $i++){
        if($collection->books[$i]->bookId == $bookId){
            unset($collection->books[$i]);
        }
    }
    $collectionStr = json_encode($collection);
//Luu lai
    $handle = fopen($collectionFile, "w+");
    $collectionStr = json_encode($collection);
    fwrite($handle, $collectionStr);
    fclose($handle);

    if(recursive_remove_directory($bookId)){
        $result = "true";
    }
    else{
        $result = "false";
    }

}

function recursive_remove_directory($directory, $empty=FALSE)
{
    if(substr($directory,-1) == '/')
    {
        $directory = substr($directory,0,-1);
    }
    if(!file_exists($directory) || !is_dir($directory))
    {
        return FALSE;
    }elseif(is_readable($directory))
    {
        $handle = opendir($directory);
        while (FALSE !== ($item = readdir($handle)))
        {
            if($item != '.' && $item != '..')
            {
                $path = $directory.'/'.$item;
                if(is_dir($path))
                {
                    recursive_remove_directory($path);
                }else{
                    unlink($path);
                }
            }
        }
        closedir($handle);
        if($empty == FALSE)
        {
            if(!rmdir($directory))
            {
                return FALSE;
            }
        }
    }
    return TRUE;
}

echo $result;
?>